import time

from locust import FastHttpUser,events,task,run_single_user,exception,between
from queue import Queue
import random


queue: Queue[int] = Queue()

@events.init.add_listener
def init(environment, **kwargs):
    for i in range(1,10001):
        queue.put(2501210000+i)

class TestUser(FastHttpUser):
    host = "http://182.92.117.199"
    student_id = 0
    wait_time = between(1,5)
    def on_start(self):

        self.student_id = queue.get(block=False)
        queue.put(self.student_id)


    @task
    def login_and_order(self):
        with self.client.post(":8080/auth/login",json={"username":str(self.student_id),"password":str(self.student_id)},catch_response=True) as response:
            try:
                if response.json()["code"]==200:
                    response.success()
                else:
                    response.failure(f"{self.student_id}登录失败 {response.json()['code']}")
            except Exception as e:
                response.failure(f"登录异常{str(e)}")
        token = response.json()["data"]["access_token"]

        self.test_order(token)

    def test_order(self,token):
        for _ in range(5):
            building_id = random.randint(1,20)
            data = {"building_id":building_id,"group_id":0}
            header = {"Authorization":"Bearer "+token}
            with self.client.post(":8081/order/create",json=data,headers=header,catch_response=True) as response:
                try:
                    response_json = response.json()
                    response.success()
                except Exception as e:
                    response.failure(str(e))
            time.sleep(0.2)

if __name__ == "__main__":
    run_single_user(TestUser)

